import React, { useState, useEffect } from 'react'
import { history } from 'umi'
import NavBarBack from '@/components/NavBarBack/NavBarBack'
import { Button, Card, Form, Input, Toast } from 'antd-mobile'
import './index.less'
import request from '@/utils/request/request';
import { RequstStatusEnum } from '@/utils/request/request.type';
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import { md5 } from 'js-md5';

/**
 * 设置密码页面组件
 * 用于用户修改密码
 */
export default function PasswordSetting() {
    const [form] = Form.useForm();
    const [visible, setVisible] = useState(false)
    const [userInfo, setUserInfo] = useState<{ account?: string }>({})

    // 组件加载时获取用户信息
    useEffect(() => {
        getUserInfo();
    }, []);

    /**
     * 获取用户信息
     */
    const getUserInfo = async () => {
        const res = await request('/newApi/user/myInfo', { method: 'GET' });
        if (res.code === RequstStatusEnum.success) {
            setUserInfo(res.data)
        }
    }

    /**
     * 表单提交处理函数
     */
    const onFinish = () => {
        resetPassword()
    }

    /**
     * 重置密码的API调用函数
     */
    const resetPassword = async () => {
        const formValue = form.getFieldsValue();
        // 表单验证
        if (!formValue.password || !formValue.passwordCertain) {
            Toast.show('不允许为空');
            return;
        }
        if ((formValue.password || formValue.passwordCertain) && (formValue.password !== formValue.passwordCertain)) {
            Toast.show('密码不一致，请检查');
            return;
        }

        // 提交密码修改请求
        let updatePasswordStatus = true;
        if (typeof formValue.password === 'string' && typeof formValue.passwordCertain === 'string') {
            const data2 = { password: md5(formValue.password) };
            const res = await request('/newApi/user/updatePwd', {
                method: 'POST',
                body: data2
            })
            updatePasswordStatus = res.code === RequstStatusEnum.success
        }

        // 处理请求结果
        if (updatePasswordStatus) {
            Toast.show('更新成功');
            history.back();
        } else {
            Toast.show('更新失败');
        }
    }

    return (
        <div style={{ padding: '46px 0' }}>
            <NavBarBack content={'设置密码'} style={{ maxWidth: '450px', background: '#fff', position: 'fixed', top: '0', width: '100%', zIndex: '99' }} />
            <div style={{ padding: '0 6px', marginTop: '60px' }}>
                <Form
                    name="form"
                    form={form}
                    layout='horizontal'
                >
                    <Form.Item
                        label='当前账号ID'
                    >
                        <div>{userInfo?.account || '-'} </div>
                    </Form.Item>
                    <Form.Item
                        name='password'
                        label='修改密码'
                        extra={
                            <div className='eye'>
                                {!visible ? (
                                    <EyeInvisibleOutline onClick={() => setVisible(true)} />
                                ) : (
                                    <EyeOutline onClick={() => setVisible(false)} />
                                )}
                            </div>}
                        rules={[
                            { type: 'string', min: 6 },
                        ]}
                    >
                        <Input placeholder='请输入新密码' type={visible ? 'text' : 'password'} />
                    </Form.Item>
                    <Form.Item
                        name='passwordCertain'
                        label='确认密码'
                        extra={
                            <div className='eye'>
                                {!visible ? (
                                    <EyeInvisibleOutline onClick={() => setVisible(true)} />
                                ) : (
                                    <EyeOutline onClick={() => setVisible(false)} />
                                )}
                            </div>}
                        rules={[
                            { type: 'string', min: 6 },
                        ]}
                    >
                        <Input placeholder='请再次输入新密码' type={visible ? 'text' : 'password'} />
                    </Form.Item>
                </Form>
                <Button onClick={onFinish} block type='submit' color='primary' size='large' style={{ marginTop: '10px' }}>
                    提交
                </Button>
            </div>
        </div >
    )
}